<?php
namespace App\Http\Controllers\Admin;

use App\Models\BannerModel;
use App\Validates\Admin\BannerValidate;

/**
 * 轮播列表
 */
class BannerController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if(request()->ajax()){
            $page = request()->input("page",1);
            if(request()->input("name")){
                $map[] = ['name','like',"%".request()->input("name")."%"];
            }
            if(request()->input("position")){
                $map[] = ['position','=',request()->input("position")];
            }
            $list = BannerModel::getBannerList($this->pageSize,$page,$map);
            if($list['data']) {
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['position'] = BannerModel::position($v['position']);
                }
            }
            return $this->rjson($list);
        }

        return view('admin/banner/index',['position'=>BannerModel::position()]);
    }

    /**
     * 显示创建资源表单页.
     *
     */
    public function create()
    {
        $id = request()->input('id');
        if($id) {
            $res = BannerModel::find($id);
            $res['picture'] = $res['picture'] ? explode(";", $res['picture']) : "";
        }
        return view('admin/banner/modify',['model'=>$res,'position'=>BannerModel::position()]);
    }


    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit()
    {
        try {
            $data = request()->post();

            $BannerValidate = new BannerValidate();
            if (!$BannerValidate->check($data)) {
                return $this->result('', 500, $BannerValidate->getError());
            }

            if($data['picture']){
                $data['picture'] = implode(";",$data['picture']);
            }
            $data['url'] = $data['url'] ? : '';
            $res = BannerModel::editBanner($data);
            return $this->result('', $res['code'], $res['msg']);
        } catch (\Exception $e) {
            return $this->result('', 500, $e->getMessage());
        }
    }


    /**
     * 删除指定资源
     *
     * @param  int  id
     * @return \think\Response
     */
    public function delete()
    {
        try {
            $id = request()->input("id");
            $res = BannerModel::destroy($id);
            if($res) {
                return $this->result("", 200, "操作成功");
            }
            return $this->result("", 500, "操作失败");
        } catch (\Exception $e) {
            return $this->result("", 500, $e->getMessage());
        }
    }
}
